﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using LDSP.BRL;
using System.Net.Mail;
using BLL.Util;
using LDSP.Util;
using LDSP.Helper;
using BYFW.WebBase;

namespace LDSP.UI
{
    public partial class Login : BRL.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string userName = LDSPCookie.GetInstance().GetCookie(Request, CookieKeys.UserName);
                string password = LDSPCookie.GetInstance().GetCookie(Request, CookieKeys.Password);

                bool fobidAutoLogin = Request.QueryString["FOBID_AUTO_LOGIN"] == "true";
                if (!fobidAutoLogin && !string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
                {
                    this.Session.Add(SessionKeys.AutoLogin, "AUTO_U_LOGIN");
                    LoginWithCookie(userName, password, string.Empty, false);
                }
            }
        }

        public override void RedirectBefore()
        {
            //Note：本页面不需要进行页面跳转判断
        }

        protected void btn_ok_Click(object sender, EventArgs e)
        {
            try
            {
                LoginWithCookie(this.txt_name.Text.Trim(), this.txt_pwd.Text, this.txt_validate.Text, this.chkRememberMe.Checked);
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        private void LoginWithCookie(string userName, string password, string validateCode, bool needWriteCookie)
        {
            if (this.Login(userName, password, validateCode, 1))
            {
                this.Session.Remove(SessionKeys.AutoLogin);

                //写cookie.
                if (needWriteCookie)
                {
                    new LDSPCookie().WriteCookie(Response, CookieKeys.UserName, this.txt_name.Text.Trim());
                    new LDSPCookie().WriteCookie(Response, CookieKeys.Password, this.txt_pwd.Text);
                }

                //页面跳转.
                string redirectUrl = string.Empty;
                if (LoginUser != null)
                {
                    if (LoginUser.UserType == EnterpriseUserType.企业管理员)
                    {
                        redirectUrl = "~/UI/EnterpriseAdmin/Index.aspx";
                    }
                    else
                    {
                        redirectUrl = "~/UI/EnterpriseCommonUser/Index.aspx";
                    }

                    this.Response.Redirect(redirectUrl);
                }
            }
        }
    }
}